import cv2
import socket
import struct
import numpy as np

# 设置服务器地址和端口
server_ip = '192.168.25.186'
server_port = 9999

try:
    # 创建socket对象
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((server_ip, server_port))
    print(f"已连接到服务器 {server_ip}:{server_port}")

    # 打开摄像头设备
    cap = cv2.VideoCapture('/dev/video20')
    if not cap.isOpened():
        raise IOError("无法打开摄像头 /dev/video20")
    
    print("开始传输视频流... (按Ctrl+C停止)")

    try:
        while True:
            # 读取帧
            ret, frame = cap.read()
            if not ret:
                print("读取帧失败，请检查摄像头连接")
                break

            # 编码为JPEG格式
            success, buffer = cv2.imencode('.jpg', frame)
            if not success:
                print("图像编码失败")
                continue 

            # 转换为字节流
            image_bytes = buffer.tobytes()
            size = len(image_bytes)

            try:
                # 发送数据包大小
                client_socket.sendall(struct.pack('>I', size))
                # 发送图像数据
                client_socket.sendall(image_bytes)
            except (BrokenPipeError, ConnectionResetError):
                print("服务器连接已断开")
                break
            except Exception as e:
                print(f"发送数据时出错: {str(e)}")
                break

    except KeyboardInterrupt:
        print("用户中断，停止传输")
    
except Exception as e:
    print(f"程序出错: {str(e)}")

finally:
    if 'cap' in locals() and cap.isOpened():
        cap.release()
        print("摄像头已释放")
    if 'client_socket' in locals():
        client_socket.close()
        print("Socket连接已关闭")